package cn.wolfcode.wolf2world.service.impl;

import cn.wolfcode.wolf2world.domain.TravelComment;
import cn.wolfcode.wolf2world.query.TravelCommentQueryObject;
import cn.wolfcode.wolf2world.repository.TravelCommentRepository;
import cn.wolfcode.wolf2world.service.TravelCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author 杨兴健
 * @Date 2020-08-16 22:14
 */
@Service
public class TravelCommentServiceImpl implements TravelCommentService {
    @Autowired
    private TravelCommentRepository travelCommentRepository;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(TravelComment travelComment) {
        travelComment.setId(null);
        travelCommentRepository.insert(travelComment);
    }

    @Override
    public void update(TravelComment travelComment) {
        travelCommentRepository.save(travelComment);
    }

    @Override
    public void delete(String id) {
        travelCommentRepository.deleteById(id);
    }

    @Override
    public TravelComment get(String id) {
        return travelCommentRepository.findById(id).orElse(null);
    }

    @Override
    public List<TravelComment> list() {
        return travelCommentRepository.findAll();
    }

    /**
    * 游记评论高级查询
    * @param qo 查询条件
    * @return
    */
    @Override
    public Page<TravelComment> query(TravelCommentQueryObject qo) {

        Query query = new Query();

        long count = mongoTemplate.count(query, TravelComment.class);
        if (count == 0) {
            return Page.empty();
        }

        Pageable pageRequest = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"sequence");
        query.with(pageRequest);
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);
        return new PageImpl<TravelComment>(list,pageRequest,count);
    }

    /**
     * 新增或编辑游记评论
     * @param travelComment
     */
    @Override
    public void saveOrUpdate(TravelComment travelComment) {
        if (StringUtils.hasLength(travelComment.getId())) {
            //编辑
            this.update(travelComment);
        }else {
            //新增
            this.save(travelComment);
        }
    }

    /**
     * 根据游记id获取所有评论
     * @param travelId
     * @return
     */
    @Override
    public List<TravelComment> queryByTravelId(String travelId) {
        return travelCommentRepository.findByTravelId(travelId);
    }
}
